<template>
  <view class="food">
    <view class="title">今天吃什么？</view>
    <view class="content">
      <image :src="src"
            mode="aspectFill" />
    </view>
    <view class="name">{{name}}</view>
    <button v-if="!restart"
            @click="stop">就吃这个</button>
    <button v-else
            @click="start">我要重选</button>
  </view>
</template>

<script>
import { getRandomFood } from "@/api/food";
export default {
  name: "food",
  data() {
    return {
      src: "", // 图片url
      restart: false, // 重启标志
      list: [],
      T: undefined, // 定时器
      imgnumb: 0, // 图片索引
      name: "", // 图片名称
    };
  },
  mounted() {
	  console.log('mounted')
    this.T = setInterval(this.imgfor, 200);
    this.getFood();
  },
  onHide(){
	this.clearfun()
  },
  // onShow() {
	//   console.log('noshow')
	//   if(!this.T) {
	// 	 this.T = setInterval(this.imgfor, 150);
	//   }
  // },
  methods: {
    getFood() {
      getRandomFood().then((res) => {
        console.log(res);
        if (res.code !== 200) {
          uni.showToast({
            title: res.message,
            icon: "none",
          });
        }
        this.list = res.data;
      });
    },
    clearfun() {
      clearInterval(this.T);
	  // console.log(this.T)
	  this.T = undefined
    },
    imgfor() {
      this.src = this.list[this.imgnumb];
      if(this.src) {
        const names = this.src.split("/");
        this.name = names[names.length - 1].split(".")[0];
      }
      this.imgnumb++;
      if (this.imgnumb === this.list.length - 1) {
        this.imgnumb = 0;
      }
    },
    stop() {
      this.clearfun();
      this.restart = true;
    },
    start() {
		if (!this.T) {
			this.T = setInterval(this.imgfor, 200);
		}
      this.restart = false;
    },
  },
};
</script>

<style lang='scss'>
page {
  position: relative;
  height: 100%;
}
.food {
  width: 100%;
  .title {
    color: $theme-color;
    font-size: 50rpx;
    text-align: center;
    margin: 50rpx;
  }
  .content {
    box-sizing: border-box;
    padding: 0 20px;
    height: 200px;
    image {
      height: 100%;
      width: 100%;
      border-radius: 10px;
    }
  }

  button {
    position: absolute;
	  background-color: $theme-color;
  	color: #FFFFFF;
    left: 50%;
    bottom: 20vw;
  	transform: translateX(-50%);
  	width: 600rpx;
	  font-size: 14px;
    &::after {
      border: none;
    }
  }

  .name {
    text-align: center;
    font-size: 50rpx;
    color: #666666;
    margin-top: 20rpx;
  }
}
</style>